package cn.chenc.framework.mybatisplus.xss;


import cn.chenc.framework.core.exception.CustomException;
import cn.chenc.framework.core.model.response.CustomCode;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author Xjt
 * @Date 2021/2/26 20:45
 * @Version 1.0
 */
public class SqlFilter {

    /**
     * 处理 SQL 注入问题，对字符串进行 SQL 过滤
     * @param str 待验证字符串
     * @return 过滤后的字符串
     */
    public static String sqlInject(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }

        // 去掉 ` " ; \ 字符
        str = StringUtils.replace(str, "`", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        // 转换成小写
        str = str.toLowerCase();

        // 非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        for (String keyword : keywords) {
            if (str.contains(keyword)) {
                throw new CustomException((new CustomCode(false,50,"参数包含非法字符")));
            }
        }
        return str;
    }

}
